package com.lhj.bootdemo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lhj
 * @version 1.0
 * @date 2022/1/17 11:31 上午
 * @description: 远程调用python服务
 */

@Component
public class RpcService {

    private static Logger logger = LoggerFactory.getLogger(RpcService.class);

//    @Value("${calculate.server.host}")
//    private String HOST;
//    @Value("${calculate.server.ports.port1}")
//    private int PORT;

    public Object remoteCall(String content, String ip, int port) {
        // 访问服务进程的套接字
        Socket socket = null;
        List<String> questions = new ArrayList<>();
        logger.info("调用远程接口:host=>" + ip + ",port=>" + port);
        try {
            // 初始化套接字，设置访问服务的主机和进程端口号，HOST是访问python进程的主机名称，可以是IP地址或者域名，PORT是python进程绑定的端口号
            socket = new Socket(ip, port);
            // 获取输出流对象
            OutputStream os = socket.getOutputStream();
            PrintStream out = new PrintStream(os);
            // 发送内容
            out.print(content);
            // 告诉服务进程，内容发送完毕，可以开始处理
            out.print("over");
            // 获取服务进程的输入流
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String tmp = null;
            StringBuilder sb = new StringBuilder();
            // 读取内容
            while ((tmp = br.readLine()) != null)
                sb.append(tmp).append('\n');
            // 解析结果
            String s = sb.toString();
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) socket.close();
            } catch (IOException e) {
            }
            logger.info("远程接口调用结束.");
        }
        return null;
    }
}
